<!--suppress NpmUsedModulesInstalled, JSUnresolvedVariable -->
<template>
  <div class="app-container">
    <el-button @click="addVideo" size="small" type="success" class="el-icon-circle-plus" style="margin-bottom: 10px">添加视频</el-button>
    <el-button @click="batchChangeVideoState(1)" size="small" type="primary" class="el-icon-caret-top" style="margin-bottom: 10px">一键发布</el-button>
    <el-button @click="batchChangeVideoState(0)" size="small" type="warning" class="el-icon-caret-bottom" style="margin-bottom: 10px">一键下架</el-button>
    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="videoList"
      :default-sort = "{prop: 'gmtModified', order: 'descending'}"
      element-loading-text="数据加载中"
      border
      fit
      highlight-current-row>

      <el-table-column
        label="序号"
        width="60"
        align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="title" label="名称" width="100" align="center"/>

      <el-table-column label="视频封面" width="520" align="center">

        <template slot-scope="scope">
          <el-upload
            class="avatar-uploader"
            :action="BASE_API+'/itservice/imageadmin'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess.bind(this,scope.row.id)"
            :before-upload="beforeAvatarUpload">
            <img :alt="scope.row.title" v-if="scope.row.videoCover" :src="scope.row.videoCover" class="avatar" style="width: 500px; height: 300px" title="点击更换视频封面">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </template>

      </el-table-column>

      <el-table-column prop="sort" label="热度" sortable width="80" align="center"/>

      <el-table-column prop="sort" label="播放量" sortable width="100" align="center"/>

      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.state === 0 ? '未发布' : '已发布' }}
          <br>
          <el-switch
            title="更改状态"
            v-model="scope.row.state.toString()"
            style="margin-top:15px"
            active-value="1"
            inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeState(scope.row.id)"/>
        </template>
      </el-table-column>

      <el-table-column prop="gmtCreate" label="添加时间" sortable align="center"/>

      <el-table-column prop="gmtModified" label="修改时间" sortable align="center"/>

      <el-table-column label="操作" align="center" width="100">
        <template slot-scope="scope">

          <router-link :to="'/video/add/'+scope.row.id">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              title="编辑视频"></el-button>
          </router-link>
          <br><br>
          <el-button
            type="success"
            size="small"
            icon="el-icon-caret-right"
            @click="playVideo(scope.row.videoUrl)"
            title="播放视频"></el-button>
          <br><br>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            @click="removeMysqlAndTencentVideo(scope.row.id,scope.row.videoSourceId)"
            title="删除视频"></el-button>

        </template>

      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      style="padding: 30px 0; text-align: center;"
      layout="total, prev, pager, next, jumper"
      @current-change="getList"
    />
  </div>

</template>


<script>
import videoApi from '@/api/video'

export default {

  data() {
    return {
      videoList: [],
      page: 1, // 当前页
      limit: 10000, // 每页记录数
      total: 0,
      BASE_API: process.env.BASE_API// 获取dev.env.js端口号
    }
  },

  created() {
    this.getList()
  },

  methods: {

    //改变状态
    changeState(id) {
      this.$confirm('确定更改该视频状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除成功
        videoApi.changeState(id)
          .then(response => {
            // 提示信息
            this.$message({
              type: 'success',
              message: '视频状态更改成功!'
            })
            // 刷新并回到当前页
            this.getList()
          })
      })
    },

    //播放视频
    playVideo(url) {
      this.$confirm('将重新打开新标签页播放此视频, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(url, '_blank')
      })
    },

    //添加图片
    addVideo() {
      this.$router.push({ path: '/video/add' })
    },

    handleAvatarSuccess(idx, res, file, name) {
      console.log("============上传文件=============")
      console.log("idx = ", idx)
      console.log("res = ",res)
      console.log("file = ",file)
      console.log("name = ",name)
      console.log("res = ",res.data.url)
      console.log("list = ",this.videoList)
      let index = -1
      for (let i = 0; i <this.videoList.length; i++) {
        if(idx===this.videoList[i].id) {
          this.videoList[i].videoCover = res.data.url
          index = i
        }
      }
      console.log("list = ",this.videoList)

      videoApi.updateVideoCover(this.videoList[index])
        .then(response => {
          this.$message({
            message: "视频封面上传成功",
            type: "success"
          })
        })
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },


    // 课程列表的方法
    // page=1
    getList(page = 1) {
      this.page = page // 分页修改参数
      videoApi.getPageVideo(this.page, this.limit)
        .then(response => {

          this.videoList = response.data.items
          this.total = response.data.total

          this.$notify({
            message: "查询到" + this.videoList.length + "个视频",
            type: "success"
          })

          console.log("============获取列表============")
          console.log(this.videoList)
          console.log(this.total)
        })
    },

    // 删除视频
    removeMysqlAndTencentVideo(videoId, fileId) {
      this.$confirm('此操作将永久删除该视频, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 先删除数据库视频
        videoApi.deleteVideoById(videoId)
          .then(response => {
            videoApi.removeTencentVideo(fileId)
              .then(res => {
                // 提示信息
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                // 刷新并回到当前页
                this.getList()
              })
          })
      })
    },

    //一键发布
    batchChangeVideoState(state) {
      let upVideoNum = 0
      let downVideoNum = 0
      for (let i = 0; i < this.videoList.length; i++) {
        if (this.videoList[i].state===1) {
          upVideoNum++
        } else {
          downVideoNum++
        }
      }
      if (state===1) {
        if(downVideoNum===0) {
          this.$message({
            message: "当前无未上架视频！",
            type: "warning"
          })
          return
        }
        this.$confirm('当前有'+downVideoNum+'个视频未上架，是否一键上架这'+downVideoNum+'个视频？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          videoApi.batchChangeVideoState(state)
            .then(response => {
              this.$message({
                message: downVideoNum+"个视频上架成功",
                type: "success"
              })
              this.getList()
            })
        })
      } else {
        if(upVideoNum===0) {
          this.$message({
            message: "当前无已上架视频！",
            type: "warning"
          })
          return
        }
        this.$confirm('当前有'+upVideoNum+'个视频已上架，是否一键下架这'+upVideoNum+'个视频？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          videoApi.batchChangeVideoState(state)
            .then(response => {
              this.$message({
                message: upVideoNum+"个视频下架成功",
                type: "success"
              })
              this.getList()
            })
        })
      }
    }
  }
}
</script>

<style>
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

